﻿using System;
using System.Collections.Generic;
using System.Linq;
using YuYuKiCms.Dal.Interface;
using YuYuKiCms.Dal.Model;

namespace YuYuKiCms.Dal.Repository
{
    internal class PageRepository : BaseRepository<PageMenu>, IPageRepository
    {
        #region Constructor

        public PageRepository(IYuyukiModelUnitOfWork db)
            : base(db)
        {
        }

        #endregion

        public void Delete(int id)
        {
            var ob = Db.PageMenus.FirstOrDefault(f => f.Id == id);
            if (ob != null)
            {
                // all children has a new parent
                foreach (var page in Db.PageMenus.Where(f => f.IdParent == id))
                {
                    page.IdParent = page.IdParent;
                }

                // Delete current child
                Db.Delete(ob);
                Db.SaveChanges();
            }
        }

        public IEnumerable<PageMenu> GetChildren(int? parentId)
        {
            return Db.PageMenus
                .Where(w => w.IdParent == parentId)
                .OrderBy(o => o.Rank);
        }

        public bool IsUrlUniq(string urlTitle)
        {
            return !Db.PageMenus.Any(f => f.UrlTitle.Equals(urlTitle, StringComparison.InvariantCultureIgnoreCase));
        }
    }
}